<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <link rel="icon" href="/favicon.ico">
    <link rel="stylesheet" href="/resources/layui/css/layui.css" media="all"/>
    <link rel="stylesheet" href="/resources/css/public.css" media="all"/>
    <link rel="stylesheet" href="/resources/layui_ext/dtree/dtree.css" media="all"/>
    <link rel="stylesheet" href="/resources/layui_ext/dtree/font/dtreefont.css" media="all"/>
</head>
<body class="childrenBody">
<!-- 查询条件开始-->
<form class="layui-form">
    <blockquote class="layui-elem-quote quoteBox">
        <form class="layui-form" id="searchForm">
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">用户名称</label>
                    <div class="layui-input-inline">
                        <input type="text" name="loginname" id="search_loginName" class="layui-input searchVal"
                               placeholder="请输入用户名称"/>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">真实名称</label>
                    <div class="layui-input-inline">
                        <input type="text" name="name" id="search_name" class="layui-input searchVal"
                               placeholder="请输入真实名称"/>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">开始时间</label>
                    <div class="layui-input-inline">
                        <input type="text" name="startTime" id="startTime" class="layui-input searchVal" readonly
                               placeholder="开始时间"/>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">结束时间</label>
                    <div class="layui-input-inline">
                        <input type="text" name="endTime" id="endTime" class="layui-input searchVal" readonly
                               placeholder="结束时间"/>
                    </div>
                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-input-block" style="text-align: center;">
                    <button type="button" class="layui-btn" lay-submit lay-filter="doSearch">
                        <span class="layui-icon layui-icon-search"></span>查询
                    </button>
                    <button type="reset" class="layui-btn layui-btn-warm" id="resetSearch">
                        <span class="layui-icon layui-icon-refresh-1"></span>重置
                    </button>
                </div>
            </div>
        </form>
    </blockquote>
</form>
<!-- 查询条件结束-->


<!-- 数据表格开始 -->
<div>
    <table class="layui-hide" id="userTable" lay-filter="userTable"></table>
    <!-- 工具栏 -->
    <div id="userToolBar" style="display: none;">
        <button type="button" lay-event="add" class="layui-btn layui-btn-sm"><span
                class="layui-icon layui-icon-add-1"></span>添加用户
        </button>
    </div>

    <div id="userRowBar" style="display: none;">
        <button type="button" lay-event="update" class="layui-btn layui-btn-sm">
            <span class="layui-icon layui-icon-edit"></span>更新
        </button>
        <button type="button" lay-event="delete" class="layui-btn layui-btn-sm layui-btn-danger">
            <span class="layui-icon layui-icon-delete"></span>删除
        </button>
        <button type="button" lay-event="resetPwd" class="layui-btn layui-btn-sm">
            <span class="layui-icon layui-icon-refresh"></span>重置密码
        </button>
        <button type="button" lay-event="selectRole" class="layui-btn layui-btn-sm layui-btn-warm">
            <span class="layui-icon layui-icon-edit"></span>分配角色
        </button>
    </div>
</div>
<!-- 数据表格结束 -->

<!-- 添加和修改的弹出层开始 -->

<div style="display: none;padding: 5px" id="addOrUpdateDiv">
    <form class="layui-form" style="width:90%;" id="dataFrm" lay-filter="dataFrm">
        <!-- 隐藏域，保存用户id -->
        <input type="hidden" name="id" id="id">
        <div class="layui-form-item">
            <label class="layui-form-label">所属部门</label>
            <div class="layui-input-block">
                <!-- 隐藏域：保存选中部门的节点id -->
                <input type="hidden" name="deptid" id="deptid">
                <ul id="deptTree" class="dtree" data-id="0"></ul>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">领导部门</label>
            <div class="layui-input-block">
                <ul id="mgrTree" class="dtree" data-id="0"></ul>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">直属领导</label>
            <div class="layui-input-block">
                <select name="mgr" id="mgr">
                    <option value="0">请选择直属领导</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">用户姓名</label>
                <div class="layui-input-block">
                    <input type="text" name="name" id="name" lay-verify="required" autocomplete="off"
                           placeholder="请输入用户姓名" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">登陆名称</label>
                <div class="layui-input-block">
                    <input type="text" name="loginname" id="loginname" lay-verify="required" autocomplete="off"
                           placeholder="请输入登陆名称" class="layui-input">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">用户地址</label>
            <div class="layui-input-block">
                <input type="text" name="address" lay-verify="required" autocomplete="off" placeholder="请输入用户地址"
                       class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">用户备注</label>
            <div class="layui-input-block">
                <textarea class="layui-textarea" name="remark" id="content"></textarea>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">用户性别</label>
                <div class="layui-input-block">
                    <input type="radio" name="sex" value="1" title="男" checked="">
                    <input type="radio" name="sex" value="0" title="女">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">是否可用</label>
                <div class="layui-input-block">
                    <input type="radio" name="available" value="1" title="是" checked="">
                    <input type="radio" name="available" value="0" title="否">
                </div>
            </div>
        </div>

        <div class="layui-form-item layui-row layui-col-xs12">
            <div class="layui-input-block" style="text-align: center;">
                <button type="button" class="layui-btn" lay-submit lay-filter="doSubmit"><span
                        class="layui-icon layui-icon-add-1"></span>提交
                </button>
                <button type="button" class="layui-btn layui-btn-warm"><span
                        class="layui-icon layui-icon-refresh-1"></span>重置
                </button>
            </div>
        </div>
    </form>
</div>

<!-- 添加和修改的弹出层结束 -->

<!-- 用户分配角色弹出层  开始 -->
<div style="display: none;padding: 5px" id="selectUserRoleDiv">
    <table class="layui-hide" id="roleTable" lay-filter="roleTable"></table>
</div>
<!-- 用户分配角色弹出层  结束 -->


<script type="text/javascript" src="/resources/layui/layui.js"></script>
<script type="text/javascript">

    var tableIns;
    layui.extend({
        dtree: '/resources/layui_ext/dtree/dtree'   // {/}的意思即代表采用自有路径，即不跟随 base 路径
    }).use(['jquery', 'form', 'table', 'layer', 'dtree', 'laydate'], function () {
        var $ = layui.jquery;
        var form = layui.form;
        var table = layui.table;
        var layer = layui.layer;
        var dtree = layui.dtree;
        var laydate = layui.laydate;
        //初始化时间选择器
        laydate.render({
            elem: '#startTime',//绑定渲染的元素
            type: 'datetime'//控件选择类型
        });
        laydate.render({
            elem: '#endTime',//绑定渲染的元素
            type: 'datetime'//控件选择类型
        });

        //渲染表格
        tableIns = table.render({
            elem: "#userTable",
            url: "/sys/user/userlist",
            toolbar: '#userToolBar',
            title: '用户数据表',
            height: 'full-180',
            page: true,
            cols: [
                [
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'id', title: 'ID', align: 'center', width: 60},
                    {field: "loginname", title: '用户名', align: 'center', width: 100},
                    {field: 'name', title: '真实姓名', align: 'center', width: 120},
                    {
                        field: 'sex', title: '性别', align: 'center', templet: function (d) {
                            return d.open == 1 ? "<font color='blue'>男</font>" : "<font color='red'>女</font>";
                        }
                    },
                    {field: 'deptName', title: '部门名称', align: 'center', width: 100},
                    {field: 'mgrName', title: '直接领导', align: 'center', width: 100},
                    {field: 'address', title: '地址', align: 'center'},
                    {field: 'hiredate', title: '入职时间', align: 'center', width: 180},
                    {
                        field: 'right', title: '操作', align: 'center', toolbar: '#userRowBar', align: "center",
                        width: 400, fixed: "right"
                    }
                ]
            ],
            done: function (res, curr, count) {
                //判断当前页码是否大于1
                if (curr > 1 && res.data.length == 0) {
                    //当前页码减1
                    var pageValue = curr - 1
                    tableIns.reload({
                        page: {curr: pageValue}//修改页码
                    })
                }

            }
        })
        //监听模糊查询按钮点击事件
        form.on("submit(doSearch)", function (data) {
            tableIns.reload({
                where: data.field,
                page: {
                    curr: 1
                }
            })
        })
        //监听头部工具栏事件
        table.on("toolbar(userTable)", function (obj) {
            switch (obj.event) {
                case "add":
                    openAddUserWindow();
                    break;
            }
        });
        table.on("tool(userTable)", function (obj) {
            var data = obj.data
            switch (obj.event) {
                case "update":
                    openUpdateUserWindow(data);
                    break;
                case "resetPwd":
                    resetPwd(data)
                    break;
                case "selectRole":
                    selectRole(data)
                    break;
            }
        });
        var mainIndex, url;

        //打开添加用户窗口
        function openAddUserWindow() {
            mainIndex = layer.open({
                type: 1,
                title: "添加用户",
                area: ["800px", "450px"],
                content: $("#addOrUpdateDiv"),
                success: function () {
                    //清空表单数据
                    $("#dataFrm")[0].reset();
                    //添加的提交请求
                    url = "/sys/user/addUser";
                }
            })
        }

        //初始化所属部门的下拉菜单树
        var deptTree = dtree.renderSelect({
            width: "100%",
            elem: "#deptTree",
            url: "/sys/dept/loadDeptTreeLeft",//这儿暂时不动
            dataStyle: "layuiStyle",//使用layui数据风格
            response: {message: "msg", statusCode: 0},//修改response中返回数据的定义
            dataFormat: "list"
        });
        dtree.on("node(deptTree)", function (obj) {
            //将选中得部门id赋值给隐藏于  用于保存所选中的所属部门编号
            $("#deptid").val(obj.param.nodeId)
        })
        //初始化所属部门的下拉菜单树
        var deptTree = dtree.renderSelect({
            width: "100%",
            elem: "#mgrTree",
            url: "/sys/dept/loadDeptTreeLeft",//这儿暂时不动
            dataStyle: "layuiStyle",//使用layui数据风格
            response: {message: "msg", statusCode: 0},//修改response中返回数据的定义
            dataFormat: "list"
        });
        dtree.on("node(mgrTree)", function (obj) {
            //获取用户选中的部门Id
            var deptId = obj.param.nodeId
            //发送请求  查询改部门下的员工列表
            $.post(
                "/sys/user/loadUserByDeptId",
                {"deptId": deptId},
                function (result) {
                    var html = "<option value=''>请选择所属领导</option>"
                    for (var i = 0; i < result.data.length; i++) {
                        html += "<option value='" + result.data[i].id + "'>" + result.data[i].name + "</option>"
                    }
                    //将拼接好的标签追加到下拉列表
                    $("#mgr").html(html);
                    //重心渲染下拉菜单
                    form.render("select");
                },
                "json"
            );
        });
        var checkFlag = false;//标记是否存在，false为不存在
        //绑定登录用户名输入框的失去焦点事件
        $("#loginname").bind("blur", function () {
            //获取用户名
            var loginName = $(this).val().trim();
            if (loginName.length == 0) {
                layer.msg("登录名称不能为空");
                return;
            }
            $.post(
                "/sys/user/checkloginName",
                {"loginName": loginName}, function (result) {
                    if (result.exist) {
                        //将状态修改为true
                        checkFlag = true;
                    } else {
                        checkFlag = false;
                    }
                    layer.msg(result.message);
                },
                "json"
            );
        });
        //监听表单提交事件
        form.on("submit(doSubmit)", function (data) {
            //checkFlag为true表示存在
            if (checkFlag) {
                layer.msg("登录名称已存在，请重心输入！")
            } else {
                $.post(
                    url,
                    data.field,
                    function (result) {
                        if (result.success) {
                            tableIns.reload();
                        }
                        //提示验证信息
                        layer.msg(result.message);
                        //关闭窗口
                        layer.close(mainIndex);
                    },
                    "json"
                );
            }
        });

        //打开修改用户窗口
        function openUpdateUserWindow(data) {
            mainIndex = layer.open({
                type: 1,
                title: "修改用户",
                area: ["800px", "450px"],
                content: $("#addOrUpdateDiv"),
                success: function () {
                    //回显表单数据
                    form.val("dataFrm", data);
                    //树节点回显
                    dtree.dataInit("deptTree", data.deptid);//部门编号
                    dtree.setSelectValue("deptTree");
                    //修改的提交请求
                    url = "/sys/user/updateUser";
                    //设置用户名称输入框只读
                    $("#loginname").attr("readonly", "readonly");
                    //用户名输入框的失去焦点解绑
                    $("#loginname").unbind("blur");
                    //领导所属部门回显   获取当前用户的领导id
                    var mgrId = data.mgr;
                    $.get(
                        "/sys/user/loadUserById",
                        {"id": mgrId},
                        function (result) {
                            //返回的用户数据
                            var data = result.data
                            //树节点回显
                            dtree.dataInit("mgrTree", data.deptid);//部门编号
                            dtree.setSelectValue("mgrTree")

                            //发送请求  查询改部门下的员工列表
                            $.post(
                                "/sys/user/loadUserByDeptId",
                                {"deptId": data.deptid},
                                function (result) {
                                    var html = "<option value=''>请选择所属领导</option>"
                                    for (var i = 0; i < result.data.length; i++) {
                                        html += "<option value='" + result.data[i].id + "'>" + result.data[i].name + "</option>"
                                    }
                                    //将拼接好的标签追加到下拉列表
                                    $("#mgr").html(html);
                                    //领导数据回显
                                    $("#mgr").val(mgrId);
                                    //重心渲染下拉菜单
                                    form.render("select");
                                },
                                "json"
                            );
                        },
                        "json"
                    );
                }
            })
        }

        function resetPwd(data) {

            layer.confirm("确定要重置[" + data.name + "]的密码吗？", {"icon": 3, "title": "提示"}, function (index) {
                $.post(
                    "/sys/user/resetPwd",
                    {"id": data.id},
                    function (result) {
                        if (result.success) {
                            //刷新表格
                            tableIns.reload();
                        }
                        layer.msg(result.message);
                    },
                    "json"
                );
                layer.close(index)
            })
        }

        //分配角色窗口
        function selectRole(data) {
            mainIndex = layer.open({
                type: 1,
                title: "分配[" + data.name + "]的角色",
                area: ["800px", "450px"],
                content: $("#selectUserRoleDiv"),
                btn: ['<span class="layui-icon layui-icon-ok">确定</span>',
                    '<span class="layui-icon layui-icon-close">取消</span>'],
                yes: function (index, layero) {
                    //获取选中行
                    var checkStatus = table.checkStatus('roleTable');
                    //判断是否有选中行
                    if (checkStatus.data.length == 0) {
                        layer.msg("请选中要分配的角色")
                    } else {
                        //定义数组
                        var idArr = [];
                        //循环选中行
                        for (var i = 0; i < checkStatus.data.length; i++) {
                            idArr.push(checkStatus.data[i].id);//id是角色编号
                        }
                        //将数组拼成字符串
                        var ids = idArr.join(",");
                        $.post(
                            "/sys/user/saveUserRole",
                            {"userId": data.id, "roleIds": ids},
                            function (result) {
                                layer.msg(result.message);
                            },
                            "json"
                        )
                        //关闭当前窗口
                        layer.close(mainIndex);
                    }
                },
                btn2: function (index, layero) {
                    //按钮2(取消)的回调
                    //return false  可以做到点取消的时候不会关闭弹窗
                },
                success: function () {
                    //成功之后初始化角色列表的表格数据
                    initRoleTable(data)
                }
            })
        }
    /*    //监听表单提交事件(模糊查询)
        form.on("submit(doSearch)", function (data) {
            tableIns.reload({
                where: data.field,//条件参数
                page: {
                    curr: 1
                }
            })
        })*/

        function initRoleTable(data) {
            table.render({
                elem: "#roleTable",
                url: "/sys/user/initRoleByUserId",
                where: {
                    "id": data.id
                },
                cols: [
                    [
                        {type: 'checkbox', align: 'center'},
                        {field: 'id', title: 'ID', align: 'center'},
                        {field: "rolecode", title: '角色编码', align: 'center'},
                        {field: 'rolename', title: '角色名称', align: 'center'},
                        {field: 'remark', title: '角色备注', align: 'center'},
                    ]
                ],
            })
        }

    });

    function loadTableData(id) {
        tableIns.reload({
            where: {"id": id},
            page: {curr: 1}
        })
    }
</script>
</body>
</html>